﻿using OA.Model.DB;
using OA.Web.Areas.Admin.Controllers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Web;
using OA.Model;

namespace OA.Web.Attribute
{
    public class AdminFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var controller = context.Controller as BaseAdminController;
            controller.ViewBag.Menus = MySingle.Menus;
            AdminInfo infoAdmin = (AdminInfo)CallContext.GetData("AdminInfo");
            if (infoAdmin == null)
            {
                var accessor = (IHttpContextAccessor)CallContext.GetData("IHttpContextAccessor");
                string url = string.Empty;
                if (accessor.HttpContext.Request.Method.ToLower() == "get")
                {
                    url = "/Admin/Login/Index?url=" + HttpUtility.UrlEncode(accessor.HttpContext.Request.GetEncodedUrl());
                }
                else
                {
                    url = "/Admin/Login/Index?url=" + HttpUtility.UrlEncode(accessor.HttpContext.Request.Headers["Referer"].ToString());
                }
                if (context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    var result = new { State = 401, Msg = "" };
                    context.Result = new ContentResult() { Content = JsonConvert.SerializeObject(result) };
                }
                else
                {
                    context.Result = new RedirectResult(url);
                }
                return;
            }
            controller.ViewBag.AdminInfo = controller.Info;
            controller.ViewBag.Signature = controller.Signature;
            base.OnActionExecuting(context);
        }

    }
}
